package com.kaigejava.service;

import cn.hutool.core.date.DatePattern;
import cn.hutool.json.JSONUtil;
import com.kaigejava.commoneresult.Result;
import com.kaigejava.dto.PushParams;
import com.kaigejava.dto.SystemMessageDTO;
import com.kaigejava.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.websocket.EncodeException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import static com.kaigejava.service.RedisConstant.KEY;

/**
 * @author 凯哥Java
 * @description
 * @company
 * @since 2023/8/13 10:46
 */
@RestController
@RequestMapping("/webSocketPush")
public class WebSocketController {
    @Autowired
    private WebSocketServer webSocket;


    @Resource
    private RedisUtil redisUtil;

    @RequestMapping("/sentMessage")
    public Result sentMessage(String userId, String message){
        try {

            SystemMessageDTO dto = new SystemMessageDTO();
            dto.setTitle(message);
            String time = DatePattern.NORM_DATETIME_FORMAT.format(new Date());
            dto.setTime(time);
            dto.setStatus(0);
            //这里将消息存放到redis中
            String redisKey = KEY+userId;
            Object megObj = redisUtil.get(redisKey);
            List<SystemMessageDTO>  list = new ArrayList<>();
            if(Objects.nonNull(megObj)){
                list = JSONUtil.toList((String)megObj,SystemMessageDTO.class);
            }
            list.add(dto);
            //存放到redis中
            redisUtil.set(redisKey,JSONUtil.toJsonStr(list));
            webSocket.addTotalAndSendMessageTotalByUserId(userId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.ok("SUCCESS");

    }



    /***
     * 功能描述:
     * 根据用户ID更新ws推送的参数
     * @Author: LXD
     * @Date: 2022-12-01 09:21:25
     * @Param  userId: WS中的用户ID
     * @Param pushParams: 推送参数
     * @return: void
     * @since: 1.0.0
     */
    @RequestMapping("/changeWsParams")
    public void changeWsParams(String userId, PushParams pushParams){
        try {
            webSocket.changeParamsByUserId(userId,pushParams);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (EncodeException e) {
            e.printStackTrace();
        }

    }
}
